import { SyntheticEvent, useEffect, useRef, useState } from "react";

const getBigList = (n: number) => {
  const bigList = [];
  for (let i = 0; i < n; i++) {
    bigList.push(i);
  }
  return bigList;
};

const App = () => {
  const bigList = getBigList(100000);
  const screenHeight = 300;
  const itemHeight = 30;
  const [scrollTop, setScrollTop] = useState(0);
  const containerRef = useRef<HTMLDivElement>(null);
  const [list, setList] = useState<number[]>([]);
  const handleScroll = (e: Event) => {
    const scrollTop = (e.currentTarget as HTMLElement).scrollTop;
    setScrollTop(scrollTop)
  };
  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      const start = Math.ceil(scrollTop / itemHeight);
      const renderItemNumber = Math.ceil(screenHeight / itemHeight);
      const end = start + renderItemNumber;
      setList(bigList.slice(start, end));
      container.addEventListener("scroll", (event: Event) =>
        handleScroll(event)
      );
    }
    return () => {
      if (container) {
        container.removeEventListener("scroll", (event: Event) =>
          handleScroll(event)
        );
      }
    };
  }, [scrollTop]);
  return (
    <div>
      <h1>Big List</h1>
      <div
        style={{
          width: "315px",
          height: `${screenHeight + 15}px`,
          overflow: "scroll",
        }}
        ref={containerRef}
      >
        <ul
          style={{
            margin: 0,
            padding: 0,
            height: `${itemHeight * bigList.length}px`,
          }}
        >
          <div
            style={{
              position: "relative",
              top: `${scrollTop}px`,
            }}
          >
            {list.map((item) => (
              <li key={item} style={{ height: `${itemHeight}px` }}>
                item {item}
              </li>
            ))}
          </div>
        </ul>
      </div>
    </div>
  );
};

export default App;
